package com.zaofan.service;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zaofan.bean.Account;
import com.zaofan.bean.Dynamic;
import com.zaofan.bean.DynamicDTO;
import com.zaofan.bean.DynamicReply;
import com.zaofan.bean.DynamicReplyDTO;
import com.zaofan.bean.Topic;
import com.zaofan.bean.UserImage;
import com.zaofan.constant.TopicConstant;
import com.zaofan.dao.DynamicDao;
import com.zaofan.dao.TopicDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.mobile.bean.DynamicDetail;
import com.zaofan.mobile.bean.Fans;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.SqlBuilderUtils;
import com.zaofan.utils.WebUtils;

public class DynamicService {
	private DynamicDao dynamicDao = new DynamicDao();
	private DynamicReplyService replyService = new DynamicReplyService();
	private AccountService accountService = new AccountService();
	private TopicDao topicService = new TopicDao();

	public void delete(Dynamic dynamic) {
		dynamicDao.del(dynamic);
	}

	public void add(Dynamic dynamic) throws ServiceException {
		dynamic.setCount(0);
		dynamic.setPraise(0);
		dynamic.setAddTime(new Date());
		dynamic.setType(TopicConstant.TOPIC_TYPE_NORMAL);
		dynamicDao.add(dynamic);
	}

	public void update(Dynamic dynamic) {
		dynamicDao.update(dynamic);
	}

	public void updateDynamic(Dynamic dynamic) throws ServiceException {
		if (WebUtils.isEmpty(dynamic.getId())) {
			throw new ServiceException("请输入id");
		}
		Dynamic target = this.findById(dynamic.getId());
		// if (target == null) {
		// throw new ServiceException("请输入id");
		// }
		// if (!WebUtils.isEmpty(dynamic.getTitle())) {
		// target.setTitle(dynamic.getTitle());
		// }
		// if (!WebUtils.isEmpty(dynamic.getDes())) {
		// target.setDes(dynamic.getDes());
		// }
		// if (!WebUtils.isEmpty(dynamic.getContent())) {
		// target.setContent(dynamic.getContent());
		// }
		// if (!WebUtils.isEmpty(dynamic.getImage())) {
		// target.setImage(dynamic.getImage());
		// }
		// if (!WebUtils.isEmpty(dynamic.getBigImage())) {
		// target.setBigImage(dynamic.getBigImage());
		// }
		// if (dynamic.getType() != 0) {
		// target.setType(dynamic.getType());
		// }
		dynamicDao.update(target);
	}

	public List<Dynamic> findAll(Map<String, Object> params) {
		List<Dynamic> data = dynamicDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return dynamicDao.count(params);
	}

	public Dynamic findById(int id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id + "");
		return dynamicDao.findOne(params);
	}

	public List<DynamicDTO> findAll(String begin, String end, String userMobile, String userName) {
		return dynamicDao.findAll(begin, end, userMobile, userName);
	}

	public Long count(String userMobile, String userName) {
		return dynamicDao.count(userMobile, userName);
	}

	public List<com.zaofan.mobile.bean.Dynamic> findJingxuanDynamic(int begin, int end) {
		List<com.zaofan.mobile.bean.Dynamic> dynamics = dynamicDao.findJingxuanDynamic(begin, end);
		if (dynamics == null) {
			dynamics = new ArrayList<>();
		}
		return dynamics;
	}

	public List<com.zaofan.mobile.bean.Dynamic> getNewDynamics(int begin, int end) {
		List<com.zaofan.mobile.bean.Dynamic> dynamics = dynamicDao.getNewDynamics(begin, end);
		if (dynamics == null) {
			dynamics = new ArrayList<>();
		}
		return dynamics;
	}

	public List<Fans> findTop4Activity() {
		List<Fans> fans = dynamicDao.findTop4Activity();
		if (fans == null) {
			fans = new ArrayList<>();
		}
		return fans;
	}

	public DynamicDetail getDynamicDetail(int id) {
		DynamicDetail detail = dynamicDao.getDynamicDetail(id);
		if (detail == null) {
			return null;
		}
		List<DynamicReplyDTO> praises = replyService.findByDynamicIdWithOther(0 + "", 5 + "", id + "", 0 + "", null);
		detail.setPraises(praises);
		List<DynamicReplyDTO> replys = replyService.findByDynamicIdWithOther(0 + "", 10 + "", id + "", 1 + "", null);
		detail.setReplys(replys);
		return detail;
	}

	public void userCreateDynamic(DynamicDTO dto) throws ServiceException {
		if (dto == null) {
			throw new ServiceException("参数错误!!!");
		}
		if (dto.getUserId() == 0) {
			throw new ServiceException("您还未登录,请重新登录试试!!!");
		}
		if (WebUtils.isEmpty(dto.getContent()) && WebUtils.isEmpty(dto.getImage())) {
			throw new ServiceException("不能发布没有内容的动态!!!");
		}
		Dynamic dynamic = new Dynamic();
		dynamic.setAddTime(new Date());
		dynamic.setContent(WebUtils.filter(dto.getContent()));
		dynamic.setCount(0);
		dynamic.setIsDelete(0);
		dynamic.setPraise(0);
		dynamic.setType(1);
		dynamic.setUserId(dto.getUserId());
		dynamic.setTopicId(0);
		dynamic.setAddress(dto.getAddress());
		Connection connection = C3p0DataSourceUtils.getConnection();
		try {
			try {
				connection.setAutoCommit(false);
				QueryRunner runner = new QueryRunner();
				String sql = SqlBuilderUtils.builderInsertSql(Dynamic.class, dynamic);
				runner.update(connection, sql);
				int id = 0;
				try {
					Long t = (Long) runner.query(connection, "SELECT LAST_INSERT_ID()", new ScalarHandler<Long>());
					id = t.intValue();
				} catch (Exception e) {
					BigInteger t = (BigInteger) runner.query(connection, "SELECT LAST_INSERT_ID()",
							new ScalarHandler<BigInteger>());
					id = t.intValue();
				}
				if (dto.getImage() != null && dto.getImage().length() > 0) {
					UserImage images;
					for (String image : dto.getImage().split(",")) {
						images = new UserImage();
						images.setType(0);
						images.setDynamicId(id);
						images.setImage(image);
						images.setUserId(dto.getUserId());
						sql = SqlBuilderUtils.builderInsertSql(UserImage.class, images);
						runner.update(connection, sql);
					}
				}
				connection.commit();
			} catch (Exception e) {
				e.printStackTrace();
				connection.rollback();
				throw new ServiceException("动态发布失败!!!");
			} finally {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServiceException("动态发布失败!!!");
		}
	}

	public void praiseDynamic(Integer userId, Integer id) throws ServiceException {
		Account user = accountService.findById(userId);
		if (user == null) {
			throw new ServiceException("您还未登录,请重新登录试试!!!");
		}
		Dynamic dynamic = findById(id);
		if (dynamic == null) {
			throw new ServiceException("动态不存在或已被删除,请刷新试试!!!");
		}
		if (dynamic.getIsDelete() == 1) {
			throw new ServiceException("动态不存在或已被删除,请刷新试试!!!");
		}
		dynamic.setPraise(dynamic.getPraise() + 1);
		DynamicReply reply = new DynamicReply();
		reply.setAddTime(new Date());
		reply.setContent("");
		reply.setReplyId(dynamic.getId());
		reply.setReplyType(0);
		reply.setType(TopicConstant.TOPIC_TYPE_NORMAL);
		reply.setUserId(user.getId());
		reply.setState(0);
		reply.setAuthorId(dynamic.getUserId());
		Connection connection = C3p0DataSourceUtils.getConnection();
		try {
			try {
				connection.setAutoCommit(false);
				QueryRunner runner = new QueryRunner();
				String sql = SqlBuilderUtils.builderInsertSql(DynamicReply.class, reply);
				runner.update(connection, sql);
				sql = SqlBuilderUtils.builderUpdateSql(Dynamic.class, dynamic);
				runner.update(connection, sql);
				connection.commit();
			} catch (Exception e) {
				e.printStackTrace();
				connection.rollback();
				throw new ServiceException("发布失败!!!");
			} finally {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServiceException("发布失败!!!");
		}
	}

	public void replyDynamic(Integer userId, Integer id, String content) throws ServiceException {
		if (WebUtils.isEmpty(content)) {
			throw new ServiceException("请输入评论内容!!!");
		}
		Account user = accountService.findById(userId);
		if (user == null) {
			throw new ServiceException("您还未登录,请重新登录试试!!!");
		}
		Dynamic dynamic = findById(id);
		if (dynamic == null) {
			throw new ServiceException("动态不存在或已被删除,请刷新试试!!!");
		}
		if (dynamic.getIsDelete() == 1) {
			throw new ServiceException("动态不存在或已被删除,请刷新试试!!!");
		}
		dynamic.setCount(dynamic.getCount() + 1);
		DynamicReply reply = new DynamicReply();
		reply.setAddTime(new Date());
		reply.setContent(WebUtils.filter(content));
		reply.setReplyId(dynamic.getId());
		reply.setReplyType(1);
		reply.setType(TopicConstant.TOPIC_TYPE_NORMAL);
		reply.setUserId(user.getId());
		reply.setState(0);
		reply.setAuthorId(dynamic.getUserId());
		Connection connection = C3p0DataSourceUtils.getConnection();
		try {
			try {
				connection.setAutoCommit(false);
				QueryRunner runner = new QueryRunner();
				String sql = SqlBuilderUtils.builderInsertSql(DynamicReply.class, reply);
				runner.update(connection, sql);
				sql = SqlBuilderUtils.builderUpdateSql(Dynamic.class, dynamic);
				runner.update(connection, sql);
				connection.commit();
			} catch (Exception e) {
				e.printStackTrace();
				connection.rollback();
				throw new ServiceException("发布失败!!!");
			} finally {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServiceException("发布失败!!!");
		}
	}

	public List<com.zaofan.mobile.bean.Dynamic> findDynamicByUserId(String begin, String end, int userId) {
		return dynamicDao.findDynamicByUserId(begin, end, userId + "");
	}

	public List<com.zaofan.mobile.bean.Dynamic> getFollowDynamics(Integer begin, Integer end, Integer userId) {
		return dynamicDao.getFollowDynamics(begin, end, userId);
	}

	public com.zaofan.mobile.bean.Dynamic findDynamicWithOtherById(int replyId) {
		return dynamicDao.findDynamicWithOtherById(replyId);
	}

	public Dynamic findPraiseReplyByUserIdAndReplyId(Integer userId, Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		params.put("topicId", id);
		params.put("replyType", "0");
		return dynamicDao.findOne(params);
	}

	public void delReply(Dynamic topicReply) throws Exception {
		Topic topic = topicService.findById(topicReply.getTopicId());
		if (topic == null) {
			throw new ServiceException("参数错误");
		}
		try {
			Connection connection = C3p0DataSourceUtils.getConnection();
			QueryRunner runner = new QueryRunner();
			String sql = "";
			try {
				connection.setAutoCommit(false);
				if (topicReply.getReplyType() == 0) {
					topic.setPraise(topic.getPraise() - 1);
				} else {
					topic.setCount(topic.getCount() - 1);
				}
				// 更新 话题的 相关数量
				sql = SqlBuilderUtils.builderUpdateSql(Topic.class, topic);
				System.err.println(sql);
				runner.update(connection, sql);
				sql = SqlBuilderUtils.builderDelSql(Dynamic.class, topicReply);
				System.err.println(sql);
				runner.update(connection, sql);
				connection.commit();
			} catch (Exception e) {
				connection.rollback();
				e.printStackTrace();
				throw e;
			} finally {
				connection.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public List<DynamicDTO> findByTopicIdWithOther(String begin, String end, String topicId, String replyType,
			String type) {
		List<DynamicDTO> datas = dynamicDao.findByTopicIdWithOther(begin, end, topicId, replyType, type);
		if (datas == null) {
			datas = new ArrayList<>();
		}
		return datas;
	}

	public Long countByTopicIdWithOther(String topicId, String replyType, String type) {
		return dynamicDao.countByTopicIdWithOther(topicId, replyType, type);
	}

}
